package me.zingon.MapDemo.service.impl;

import me.zingon.MapDemo.service.NetService;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by ZTC on 3/23/2017.
 */
@Service
public class NetServiceImpl implements NetService{
    @Autowired
    CloseableHttpClient httpClient;

    @Autowired
    RequestConfig requestConfig;

    @Override
    public String post(String url, Map<String,String> params) {
        int count=0;
        while(count<3) {
            try {
                HttpPost post = new HttpPost(url);
                List<NameValuePair> sendParams = new ArrayList<NameValuePair>();
                Set<Map.Entry<String, String>> set = params.entrySet();
                for (Map.Entry<String, String> e : set) {
                    sendParams.add(new BasicNameValuePair(e.getKey(), e.getValue()));
                }
                post.setEntity(new UrlEncodedFormEntity(sendParams, "UTF-8"));
                post.setConfig(requestConfig);
                CloseableHttpResponse res = httpClient.execute(post);
                String result = EntityUtils.toString(res.getEntity(), "UTF-8");
                return result;
            } catch (IOException e) {
                e.printStackTrace();
                count++;
            }
        }
        return null;
    }
}
